package servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取文件路径
        String realPath = getServletContext().getRealPath("/files/index.png");
        File file = new File(realPath);
        // 获取文件输入流
        FileInputStream inputStream = new FileInputStream(realPath);

        // 设置相关响应头
        String mimeType = getServletContext().getMimeType(realPath);
        System.out.println(mimeType);
        resp.setContentType(mimeType);

        String fileName = "tu.png";
        String encodeName = URLEncoder.encode(fileName, "UTF-8");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"");
        // 设置文件长度
        resp.setContentLength((int) file.length());

        ServletOutputStream outputStream = resp.getOutputStream();
        // 将文件输入流通过输出流输出
        byte[] bs = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(bs)) !=-1) {
            outputStream.write(bs, 0, len);
        }

        inputStream.close();
        outputStream.close();
    }
}
